<?php

namespace App\Models\CacheModel\chat;

use App\Models\Api\BaseCache;
use App\Models\Api\Recode;
use traits\model\SoftDelete;
use AstroTool\Cache\CacheManage;

class HzChatRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.hz_chat_record';

    protected $cacheModel = 'chat.chat_id';

    use SoftDelete;

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        if ($ids)
        {   // 获取未删除 的数据
            $where = ['id' => ['in', $ids]];
        } else
        {   // 获取指定pid  未删除 且 未隐藏的数据
            $where = ['uid' => $type[0]];
        }
        $field = 'uid,rid,rid2,last_chat_detail_id,last_chat_detail_time,create_time,update_time';
        try
        {
            $data = $this
                ->field($field)
                ->where($where)
                ->order('update_time', $sortType)
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'rid', 'rid2', 'uid', 'last_chat_detail_id', 'last_chat_detail_time', 'create_time', 'update_time']);
        }

        return $data;
    }

    /**
     * 初始化 会话ID
     * @param array $data
     * @return int
     */
    public function initSave(array $data): int
    {
        try
        {
            $chatId = $this->insertGetId($data);

            if ($data['rid'])
            {
                CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('rid_chat_id', $data['rid'])->rmCache('rid_chat_id');
            } else
            {
                CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('uid_chat_id', $data['uid'])->rmCache('uid_chat_id');
            }
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $data['uid'])->rmCache('list');
            return (int)$chatId;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    public function updateData($chatId, $uid, $data)
    {
        try
        {
            $data['update_time'] = time();
            $this->where(['id' => $chatId])->update($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $chatId)->rmCache();
            // 更新排序顺序
            $this->listDataAdd($uid, [$chatId => $data['update_time']]);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 对话记录删除
     * @param int $uid
     * @param int $rid
     * @param int $chatId
     * @return bool
     * @throws \Exception
     */
    public function delChat(int $uid, int $rid, int $chatId): bool
    {
        try
        {
            $this::destroy($chatId);
        }
        catch (\Exception $e)
        {
            return false;
        }
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache('list');
        CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('uid_chat_id', $uid)->rmCache('uid_chat_id');
        if ($rid)
        {
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('rid_chat_id', $rid)->rmCache('rid_chat_id');
        }
        return true;
    }

    /**
     * 获取指定档案的会话ID chatId
     * @param int $rid
     * @return int
     * @throws \Exception
     */
    public function getChatIdByRid(int $rid): int
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('rid_chat_id', $rid)
            ->getDataAndSet(function () use ($rid)
            {
                try
                {
                    $id = $this->where('rid', $rid)->order('id desc')->value('id');
                    if ($id)
                    {
                        $data = ['id' => $id];
                    } else
                    {
                        $data = ['id' => 0];
                    }
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $data = ['id' => 0];
                }
                return $data;
            }, [], 'rid_chat_id');
        return (int)($data['id'] ?? 0);
    }

    /**
     * 获取用户没有自己档案的会话ID chatId
     * @param int $uid
     * @return int
     * @throws \Exception
     */
    public function getChatIdByUid(int $uid): int
    {   // 必须没有自己的档案才调用  不然会出错
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('uid_chat_id', $uid)
            ->getDataAndSet(function () use ($uid)
            {
                try
                {
                    $id = $this->where('uid', $uid)->where('rid', 0)->order('id desc')->value('id');
                    if ($id)
                    {
                        $data = ['id' => $id];
                    } else
                    {
                        $data = ['id' => 0];
                    }
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $data = ['id' => 0];
                }
                return $data;
            }, [], 'uid_chat_id');
        return (int)($data['id'] ?? 0);
    }

    /**
     * 分页数据 重组
     * @param array $data
     * @return array
     * @throws \Exception
     */
    public function pageDataResert(array $data)
    {
        $crIds = array_column($data, 'last_chat_detail_id');
        $chatRecodeDetailList = [];
        if ($crIds)
        {
            $chatRecodeDetailList = (new HzChatRecordDetails())->batchGetInfoByIds($crIds, ['content']);
        }
        $resData = [];
        $recodeModel = new Recode();
        foreach ($data as $datum)
        {
            if (!$datum['rid'])
            {
                continue;
            }
            $recodeInfo = $recodeModel->getRecode(['id' => $datum['rid']]);
            $message = 'Hi，我是准准，尝试与我对话吧';
            if ($datum['last_chat_detail_id'])
            {
                $message = isset($chatRecodeDetailList[$datum['last_chat_detail_id']]) ? $chatRecodeDetailList[$datum['last_chat_detail_id']]['content'] : $message;
            }
            $resData[] = [
                'rid' => (int)$datum['rid'],
                'avatar' => $recodeInfo['avatar'],
                'nickname' => $recodeInfo['name'],
                'message' => $message,
            ];
        }

        return $resData;
    }
}
